package cn.da.shuai.cool.common.web.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import cn.da.shuai.cool.common.web.wrapper.ReusableRequestWrapper;

import java.io.IOException;

/**
 * 请求体缓存过滤器
 * 将所有请求包装为ContentCachingRequestWrapper，以便后续处理器可以多次读取请求体
 */
@Slf4j
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class RequestBodyCachingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 只对JSON请求进行包装
        if (isJsonContentType(request) && !(request instanceof ReusableRequestWrapper)) {
            ReusableRequestWrapper wrappedRequest = new ReusableRequestWrapper(request);
            log.debug("Request wrapped as ReusableRequestWrapper: {}", request.getRequestURI());
            filterChain.doFilter(wrappedRequest, response);
        } else if (request.getRequestURI().equals("/favicon.ico")) {
            log.debug("Request to /favicon.ico, skip filter");
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 判断是否为JSON请求
     */
    private boolean isJsonContentType(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.contains(MediaType.APPLICATION_JSON_VALUE);
    }
}